package com.andnnl.pool.retry;

import com.andnnl.pool.Msg;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class RetryMsg<T> implements Delayed {
    private Msg<T> msg;
    private String key;
    private long sourceDuration;//任务持续时间
    private long delayTime;// 延迟ms
    private TimeUnit delayTimeUnit = TimeUnit.MILLISECONDS;
    /**
     * 延时执行DelayQueue的task
     *
     * @param msg
     */
    public RetryMsg(Msg<T> msg) {
        this.msg = msg;
        resetSourceDuration();
    }
    /**
     * 延时执行DelayQueue的task
     *  @param msg
     * @param delayTime  延时时长(毫秒)
     * @param key
     */
    public RetryMsg(Msg<T> msg, long delayTime, String key) {
        this.msg = msg;
        this.key = key;
        this.delayTime = delayTime;
        resetSourceDuration();
    }


    /**
     * 延时执行DelayQueue的task
     *
     * @param msg
     * @param delayTime  延时时长(毫秒)
     */
    public RetryMsg(Msg<T> msg, long delayTime) {
        this.msg = msg;
        this.delayTime = delayTime;
        resetSourceDuration();
    }
    public void resetSourceDuration() {
        this.sourceDuration = System.currentTimeMillis() + delayTimeUnit.toMillis(this.delayTime);
    }
    @Override
    public int compareTo(Delayed o) {
        if (this.getDelay(TimeUnit.MILLISECONDS) > o.getDelay(TimeUnit.MILLISECONDS)) {
            return 1;
        } else if (this.getDelay(TimeUnit.MILLISECONDS) < o.getDelay(TimeUnit.MILLISECONDS)) {
            return -1;
        }
        return 0;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(sourceDuration - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }


    public Msg<T> getMsg() {
        return msg;
    }


    public String getKey() {
        return key;
    }

    public long getDelayTime() {
        return delayTime;
    }

    public void setDelayTime(long delayTime) {
        this.delayTime = delayTime;
        resetSourceDuration();
    }
}